package git.soulbgm.common.serializer;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import git.soulbgm.common.base.BaseSerializer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author SoulBGM
 * @version 1.0
 * @date 2019/12/1 23:17
 */
public class ProtostuffSerializer implements BaseSerializer {

    private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();

    private static <T> Schema<T> getSchema(Class<T> clazz) {
        @SuppressWarnings("unchecked")
        Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
        if (schema == null) {
            schema = RuntimeSchema.createFrom(clazz);
            if (schema != null) {
                cachedSchema.put(clazz, schema);
            }
        }
        return schema;
    }

    @Override
    public <T> T deserialize(Object val, Class<T> tClass) {
        try {
            Schema<T> schema = getSchema(tClass);
            T t = schema.newMessage();
            ProtobufIOUtil.mergeFrom((byte[]) val, t, schema);
            return t;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    @Override
    public Object serialize(Object val) {
        Class clazz = val.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema schema = getSchema(clazz);
            return ProtobufIOUtil.toByteArray(val, schema, buffer);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }
}
